const cloudHelper = require('../../../../../helper/cloud_helper.js');
const pageHelper = require('../../../../../helper/page_helper.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isLoading: false,
		hasMore: true,
		page: 1,
		size: 20,
		list: []
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad() {
		this._loadList();
	},

	async _loadList() {
		if (!this.data.hasMore || this.data.isLoading) return;

		try {
			this.setData({ isLoading: true });

			const result = await cloudHelper.callCloudData('qa/history', {
				page: this.data.page,
				size: this.data.size
			});

			const list = result.list || [];
			
			this.setData({
				list: this.data.page === 1 ? list : this.data.list.concat(list),
				hasMore: list.length === this.data.size,
				page: this.data.page + 1,
				isLoad: true,
				isLoading: false
			});
		} catch (err) {
			console.error(err);
			this.setData({
				isLoad: true,
				isLoading: false
			});
			pageHelper.showModal('加载失败，请重试');
		}
	},

	/**
	 * 下拉刷新
	 */
	onPullDownRefresh() {
		this.setData({
			page: 1,
			hasMore: true,
			list: []
		});
		
		this._loadList().then(() => {
			wx.stopPullDownRefresh();
		});
	},

	onReachBottom() {
		this._loadList();
	},

	/**
	 * 点击显示详情
	 */
	bindHistoryDetail(e) {
		const id = e.currentTarget.dataset.id;
		if (!id) return;
		
		wx.navigateTo({
			url: '../detail/qa_detail?id=' + id
		});
	},

	bindUseHistory(e) {
		const question = e.currentTarget.dataset.question;
		if (!question) return;
		
		wx.navigateTo({
			url: '../index/qa_index?content=' + encodeURIComponent(question)
		});
	},

	async bindDeleteHistory(e) {
		const id = e.currentTarget.dataset.id;
		if (!id) return;
		
		try {
			await pageHelper.showConfirm('确定删除此记录？');
			
			await cloudHelper.callCloudData('qa/history/delete', {
				id
			});

			pageHelper.showSuccToast('删除成功');
			
			this.setData({
				page: 1,
				hasMore: true,
				list: []
			});
			
			this._loadList();
		} catch (err) {
			console.error(err);
		}
	},

	/**
	 * 分享
	 */
	onShareAppMessage: function() {
		return {
			title: '电力智能问答助手',
			path: '/projects/repair/pages/qa/index/qa_index'
		}
	}
}); 